package com.zlz.ddns.seddns.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.zlz.ddns.seddns.domain.DDnsUpdateRecord;
import com.zlz.ddns.seddns.domain.PublicIPCheckRecord;
import com.zlz.ddns.seddns.domain.UrlCheckEntity;
import com.zlz.ddns.seddns.mapper.DDnsCacheMapper;
import com.zlz.ddns.seddns.mapper.IPCheckRecordMapper;
import com.zlz.ddns.seddns.remote.TencentCloudDNSPodRemoteService;
import com.zlz.ddns.seddns.service.DDnsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Date;

/**
 * @Author: zhulinzhong
 * @Date: 2024/7/15
 */
@Service
public class DDnsServiceImpl implements DDnsService {

    private final IPCheckRecordMapper ipCheckRecordMapper;

    private final DDnsCacheMapper dDnsCacheMapper;

    private final TencentCloudDNSPodRemoteService tencentCloudDNSPodRemoteService;

    public DDnsServiceImpl(IPCheckRecordMapper ipCheckRecordMapper, DDnsCacheMapper dDnsCacheMapper, TencentCloudDNSPodRemoteService tencentCloudDNSPodRemoteService) {
        this.ipCheckRecordMapper = ipCheckRecordMapper;
        this.dDnsCacheMapper = dDnsCacheMapper;
        this.tencentCloudDNSPodRemoteService = tencentCloudDNSPodRemoteService;
    }

    @Override
    public String getPublicIp() {
        try {
            URL url = new URL("https://zlzblog.com/ipquery");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = in.readLine()) != null) {
                builder.append(line);
            }
            in.close();
            System.out.println("Result: " + builder);
            UrlCheckEntity urlCheckEntity = JSON.parseObject(builder.toString(), UrlCheckEntity.class);
            String ipAddress = urlCheckEntity.getIp();
            // 更新记录
            Date now = new Date();
            PublicIPCheckRecord publicIPCheckRecord = ipCheckRecordMapper.selectOne(Wrappers.<PublicIPCheckRecord>lambdaQuery()
                    .eq(PublicIPCheckRecord::getPublicIp, ipAddress));
            if (publicIPCheckRecord == null) {
                ipCheckRecordMapper.insert(PublicIPCheckRecord.builder()
                        .publicIp(ipAddress)
                        .createdTime(now)
                        .updatedTime(now)
                        .build());
                System.out.println("Insert Success：" + ipAddress);
            } else {
                ipCheckRecordMapper.update(PublicIPCheckRecord.builder().updatedTime(now).build(),
                        Wrappers.<PublicIPCheckRecord>lambdaUpdate().eq(PublicIPCheckRecord::getPublicIp, ipAddress));
            }
            return ipAddress;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean refreshTencentCloudDNSPod() throws TencentCloudSDKException {
        String publicIp = this.getPublicIp();
        if (StringUtils.isEmpty(publicIp)) {
            return false;
        }

        DDnsUpdateRecord dDnsUpdateRecord = dDnsCacheMapper.selectOne(Wrappers.<DDnsUpdateRecord>lambdaQuery().eq(DDnsUpdateRecord::getState, 0));

        // 添加解析
        Date now = new Date();
        if(dDnsUpdateRecord == null){
            DDnsUpdateRecord updateRecord = DDnsUpdateRecord.builder().state(0).oldIp("0.0.0.0").targetIp(publicIp).updatedTime(now).createdTime(now).build();
            dDnsCacheMapper.insert(updateRecord);
            tencentCloudDNSPodRemoteService.add(updateRecord);
            return true;
        }

        // 无需解析
        if(publicIp.equals(dDnsUpdateRecord.getTargetIp())){
            System.out.println("当前公网ip:" + dDnsUpdateRecord.getTargetIp() + " 未变化，无需重新解析");
            return true;
        }

        // 更新解析
        dDnsCacheMapper.updateById(DDnsUpdateRecord.builder()
                .id(dDnsUpdateRecord.getId())
                .updatedTime(now)
                .state(1)
                .build());
        dDnsUpdateRecord.setId(null);
        dDnsUpdateRecord.setOldIp(dDnsUpdateRecord.getTargetIp());
        dDnsUpdateRecord.setTargetIp(publicIp);
        dDnsUpdateRecord.setCreatedTime(now);
        dDnsUpdateRecord.setUpdatedTime(now);

        tencentCloudDNSPodRemoteService.update(dDnsUpdateRecord);
        dDnsCacheMapper.insert(dDnsUpdateRecord);

        return true;
    }
}
